<?php
/**
 *
 * User: chenzheng
 * Date: 2023/3/22
 * Time: 10:42
 */

namespace app\api\model;


use app\admin\model\MallPromotion;
use app\api\help\SendMsg;
use app\common\model\TimeModel;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class MallOrder extends TimeModel
{
    /**
     * 获取微信支付信息
     * @param $payData
     * @param $openId
     * @return array
     * @throws Exception
     */
    public static function getWechatPayInfo($payData, $openId)
    : array
    {
        //小程序
        if (empty($openId)) {
            _throwNewException('openId 不能为空');
        }
        //微信支付
        $config = Config::get('payConfig');
        $order  = [
            'out_trade_no' => $payData[ 'order_no' ],
            'description'  => 'subject-测试',
            'amount'       => [
                'total' => $payData[ 'total_amount' ],
            ],
            'payer'        => [
                'openid' => $openId,
            ],
            '_config'      => 'default', // 注意这一行
        ];
        $wechat = Pay::wechat($config)->mini($order);
        $res    = json_decode($wechat, true);
        return $res;
    }
    /**
     * 获取微信支付信息
     * @param $payData
     * @param $openId
     * @return array
     * @throws Exception
     */
    public static function getWechatPublicPayInfo($payData, $openId)
    : array
    {
        //小程序
        if (empty($openId)) {
            _throwNewException('openId 不能为空');
        }
        //微信支付
        $config = Config::get('payConfig');
        $order  = [
            'out_trade_no' => $payData[ 'order_no' ],
            'description'  => 'subject-测试',
            'amount'       => [
                'total' => $payData[ 'total_amount' ],
            ],
            'payer'        => [
                'openid' => $openId,
            ],
            '_config'      => 'default', // 注意这一行
        ];
        $wechat = Pay::wechat($config)->mp($order);
        $res    = json_decode($wechat, true);
        return $res;
    }
    /**
     * @param $order
     * @param $userId
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function resolveCollage($order, $userId)
    {
        

        $goods      = MallGoods::where('id', $order[ 'goods_id' ])->find()->toArray();
        //如果是新的拼团则增加一条拼团，否则该拼团人数加一
        if ($order[ 'u_collage_id' ] > 0) {
            $joinNum    = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('join_num');
            $collageNum = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('collage_num');
            $fail = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('fail_time');
            if ($fail==0){
                $modData = ['join_num' => ($joinNum + 1)];
                if ($collageNum == $joinNum + 1) {
                    $modData[ 'finish_time' ] = time();
                }
                if (false === MallCollage::where('collage_id', $order[ 'u_collage_id' ])->update($modData)) {
                    _throwNewException('订单支付失败');
                }
            }

        }
        //新增加一个拼团
        $startTime  = time();
        $endTime    = time() + $goods[ 'day_num' ] * 24 * 3600;
        $addCollage = [
            'goods_id'       => $order[ 'goods_id' ],
            'user_id'        => $userId,
            'collage_no'     => createCollageNo(),
            'collage_num'    => $goods[ 'collage_num' ],
            'join_num'       => 0,
            'start_time'     => $startTime,
            'end_time'       => $endTime,
            'failure_reward' => $goods[ 'failure_reward' ],
            'success_reward' => $goods[ 'success_reward' ] ?? 0,
            'create_time'    => time(),
            'update_time'    => time(),
        ];
        $collageId  = Db::name('mall_collage')->insertGetId($addCollage);
        if (false === $collageId) {
            _throwNewException('添加拼团失败');
        }
        
        
        return $collageId;
    }
    /**
     * 完成拼团
     * @param $collageId
     * @throws \think\Exception
     */
    public static function finishCollage($collageId)
    {
        $modOrder[ 'collage_status' ] = 2;
        $modOrder[ 'order_status' ]   = 30;
        $order                        = Db::name('mall_order')->where([['collage_id', '=', $collageId]])->find();
        $successReward                = MallCollage::where('collage_id', $collageId)->value('success_reward');
        
        $code = 'SMS_460786197';
        if ( !empty($code)) {
            $mobile = MallUser::where('id', $order[ 'user_id' ])->value('mobile');
            $msg    = [];
            SendMsg::sendMsg($mobile, $msg, $code);
        }
        if ($successReward > 0) {
            $modOrder[ 'success_reward' ] = $successReward;
            $balance                      = MallUser::where('id', $order[ 'user_id' ])->value('balance');
            $addBalance                   = $balance + $successReward;
            //加上余额
            if (false === MallUser::where([['id', '=', $order[ 'user_id' ]]])->update(['balance' => $addBalance])) {
                _throwNewException('订单支付失败3');
            }
            //添加交易记录
            MallTradeRecordLog::addRecord($order[ 'user_id' ], $order[ 'id' ], $successReward, $addBalance, 7);
        }
        if (false === MallOrder::where([['id', '=', $order[ 'id' ]]])->update($modOrder)) {
            _throwNewException('订单支付失败');
        }
    }
    /**
     * 处理推广奖励
     * @param $userId
     * @param $order
     */
    public static function resolvePromotion($userId, $order)
    {
        //查询推广人信息
        $promotion = Db::name('mall_promotion')->where('user_id', $userId)->find();
        if (empty($promotion)) {
            return;
        }
        if ($promotion[ 'status' ] != 1) {
            return;
        }
        //计算推广积分
        $rate       = promotionConfig('balance_rate');
        $surBalance = $rate * $order[ 'order_price' ];
        $balance    = MallUser::where('id', $userId)->value('balance');
        $addBalance = $balance + $surBalance;
        //加上余额
        if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $addBalance])) {
            _throwNewException('订单支付失败3');
        }
        //添加交易记录
        MallTradeRecordLog::addRecord($userId, $order[ 'id' ], $surBalance, $addBalance, 17, $order[ 'user_id' ]);
    }
}